﻿Imports Tajan.Monitoring.Entities

Public Class ConnectionRepository
    Inherits BaseRepository

    Public Sub Add(connection As Connection)
        Me.Context.Connections.Add(connection)
    End Sub

    Public Function GetById(connectionId As Long) As Connection
        Return (From p In Me.Context.Connections.Include("UserConnections").Include("Screen").Include("Browser") Where p.ConnectionId = connectionId).SingleOrDefault
    End Function

    Public Function GetLiveConnections() As List(Of Connection)
        Return (From p In Me.Context.Connections.Include("UserConnections").Include("Screen").Include("Browser") Where p.IsAvtive = True).ToList
    End Function

    Public Sub Disconnected(connectionId As Long)
        Dim connection = Me.GetById(connectionId)
        If connection IsNot Nothing Then
            connection.IsAvtive = False
            Me.Context.SaveChanges()
        End If
    End Sub

    Public Sub UpdateExpiredConnections()
        Dim expireDate As DateTime = Now.AddMinutes(-30)
        Dim expiredConnections = (From p In Me.Context.Connections Where p.IsAvtive = True AndAlso p.StartDate < expireDate).ToList
        For Each cnn In expiredConnections
            cnn.IsAvtive = False
            cnn.EndDate = Now
        Next
    End Sub

End Class
